package classReflectDemo;

import org.apache.log4j.Logger;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Ajie
 * @date 2020-07-08
 * @function
 */
public class ReflectHome_Reflect_Field_Method {
    private static final Logger logger = Logger.getLogger(ReflectHome_Reflect_Field_Method.class);

    //reflect field method
    public static void main(String[] args) {
        Origin jie = new Origin("jie", 18);
        try {
            Field age = jie.getClass().getDeclaredField("age");
            age.setAccessible(true);
            int mAge = (int) age.get(jie);
            logger.info("main: "+mAge);

            age.set(jie,211);//修改属性值
            logger.info("main: set reflect :"+mAge);

            Method getAgeStr = jie.getClass().getDeclaredMethod("getAgeStr");
            getAgeStr.setAccessible(true);
            logger.info("main: "+((String)getAgeStr.invoke(jie,null)));


            Method getAge = jie.getClass().getDeclaredMethod("getAge");
            getAge.setAccessible(true);
            int invokeAge = (int) getAge.invoke(jie, null);
            logger.info("main: invoke method getAge:"+invokeAge);

        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

}

class Origin{
    public String name;
    private int age;

    public Origin(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private int getAge() {
        return age;
    }

    private String getAgeStr() {
        return age+"";
    }

    public void setAge(int age) {
        this.age = age;
    }
}